import axios from 'axios';
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
// 创建axios实例
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API || '',
    // 超时
    timeout: 600000,
});

// 异常拦截处理器
const errorHandler = (error) => {
    if (error) {
        if (error.code === 'ECONNABORTED' || error.message === 'Network Error') {
            return Promise.reject(error);
        }
        console.warn('接口错误', error.response.data);
        const status = error.response.status;
        switch (status) {
            case 500:
                Promise.reject('未知的服务端错误');
                break;
            case 503:
                if (process.env.NODE_ENV !== 'govcloud') {
                    Promise.reject('服务端更新接口中,两分钟后再试');
                }
                break;
            case 400:
                Promise.reject(
                    error.response.data?.error || error.response.data?.message
                );
                break;
            default:
                if (process.env.NODE_ENV === 'development') {
                    console.log(error.response.data);
                } else {
                    Promise.reject(error.response.data.message);
                }

                break;
        }
    }
    return Promise.reject(error);
};

// request拦截器
service.interceptors.request.use((config) => {
    if (config.headers.baseAPI) {
        config.baseURL = config.headers.baseAPI;
        delete config.headers.baseAPI;
    }
    return config;
}, errorHandler);

// 响应拦截器
service.interceptors.response.use((response) => {
    const res = response.data;
    const code = (res.code && res.code.toString()) || '0';
    if (code === '0' || code === '200') {
        if (response.config.headers.needServerData) {
            return response;
        } else {
            return res;
        }
    } else {
        const error = {
            response,
        };
        errorHandler(error);
        return Promise.reject(res && res.message);
    }
}, errorHandler);

export default service;
